/**
 * Created on [2021-05-25] by zhengrr
 *
 * 项目名称: btfvilg
 *
 * 本程序版权属于福建慧政通信息科技有限公司所有。
 *
 * 任何组织和个人未经福建慧政通信息科技有限公司许可与授权,不得擅自传播、复制、更改该程序的内容。
 * 本程序受版权法和国际条约的保护。如未经授权而擅自复制或传播本程序(或其中任何部分),
 * 将受到严厉的刑事及民事制裁，并将在法律许可的范围内受到最大可能的起诉!
 *
 * ©2021 福建慧政通信息科技有限公司
 */
package com.sunnada.btfvilg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sunnada.btfvilg.config.SysConfig;
import com.sunnada.btfvilg.entity.PlanProject;
import com.sunnada.btfvilg.entity.RemoteLayer;
import com.sunnada.btfvilg.mapper.PlanProjectMapper;
import com.sunnada.btfvilg.service.PlanProjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.List;

/**
 * 规划项目信息表 服务实现类
 *
 * @author zhengrr
 */
@Service
public class PlanProjectServiceImpl extends ServiceImpl<PlanProjectMapper, PlanProject> implements PlanProjectService {

    @Resource
    private PlanProjectMapper planProjectMapper;

    @Resource
    SysConfig sysConfig;// 系统配置

    @Override
    public Integer uploadFile(MultipartFile multipartFile, String name, String land_use, String land_user) throws Exception {

        //查询是否存在同名的
        QueryWrapper<PlanProject> qw = new QueryWrapper<>();
        qw.eq("name", name);
        Integer exist = planProjectMapper.selectCount(qw);
        if (exist != null && exist > 0)
            throw new Exception("该名称已存在");

        PlanProject planProject = new PlanProject();
        planProject.setName(name);
        planProject.setLandUse(land_use);
        planProject.setLandUser(land_user);
        planProject.setRedline(0);
        planProject.setSave(0);
        LocalDateTime now = LocalDateTime.now();
        planProject.setCreateTime(now);
        planProject.setUpdateTime(now);

        // 生成保存到数据库中的相对路径
        String filePath = "/planproject/";
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        filePath = filePath + simpleDateFormat.format(calendar.getTime());

        // 如果保存的目录不存在，则创建对应的目录。
        String dir = sysConfig.getUploadDir() + filePath;
        File tmpDir = new File(dir);
        if (!tmpDir.exists()) {
            tmpDir.mkdirs();
        }

        String filename = multipartFile.getOriginalFilename();
        filePath = filePath + "/" + filename;
        planProject.setFile(filePath);

        // 生成文件的绝对路径以便保存
        String fullFilePath = sysConfig.getUploadDir() + filePath;
        java.io.File tmpFile = new java.io.File(fullFilePath);

        // 保存文件
        try {
            multipartFile.transferTo(tmpFile);
        } catch (IOException ie) {
            ie.printStackTrace();
            return 0;
        }

        // 添加相关记录到数据库并返回
        planProjectMapper.insert(planProject);
        return planProject.getId();

    }

    @Override
    public List<PlanProject> getPlanInfo() throws Exception {
        QueryWrapper<PlanProject> qw = new QueryWrapper<>();
        qw.eq("redline",0);
        List<PlanProject> planProjects = planProjectMapper.selectList(qw);
        return planProjects;
    }

    @Override
    public Integer saveNameAndState(Integer id, String name) {
        PlanProject plan = planProjectMapper.selectById(id);
        if(plan.getRedline() != 0)
            return 0;

        //
        PlanProject planProject = new PlanProject();
        planProject.setId(id);
        planProject.setName(name);
        planProject.setSave(1);
        return planProjectMapper.updateById(planProject);
    }

    @Override
    public Boolean deleteInfo(Long id) throws Exception {
        PlanProject planProject = planProjectMapper.selectById(id);
        if(planProject.getRedline() != 0)
            return false;

        // 获取文件名及其绝对路径
        String filePath = planProject.getFile();
        String fullPath = sysConfig.getUploadDir() + filePath;

        // 删除服务器文件
        File file = new File(fullPath);
        file.delete();

        int i = planProjectMapper.deleteById(id);
        return i == 1;
    }

    @Override
    public void downloadFile(Integer id, HttpServletResponse response) {
        PlanProject planProject = planProjectMapper.selectById(id);
        if (planProject == null)
            return;

        // 获取文件名及其绝对路径
        String filePath = planProject.getFile();
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
        String fullPath = sysConfig.getUploadDir() + filePath;

        // 设置下载文件名及内容长度
        File file = new File(fullPath);
//        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName);
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setContentLength((int) file.length());

        // 输出文件
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
            bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            byte[] buf = new byte[1024 * 100];
            int count = 0;
            while ((count = bufferedInputStream.read(buf)) != -1) {
                bufferedOutputStream.write(buf, 0, count);
            }
            bufferedOutputStream.flush();

        } catch (IOException ie) {
            ie.printStackTrace();
        } finally {
            try {
                if(bufferedInputStream != null)
                    bufferedInputStream.close();
            }catch (Exception e){
            }
            try {
                if(bufferedOutputStream != null)
                    bufferedOutputStream.close();
            }catch (Exception e){
            }
        }
    }

}
